<template>
  <view class="favorites-container">
    <!-- 标题栏 -->
    <view class="header">
      <text class="title">我的收藏</text>
      <text class="count">共{{ total }}个</text>
    </view>

    <!-- 收藏列表 -->
    <view class="favorites-list" v-if="favoriteList.length > 0">
      <view 
        class="favorite-item" 
        v-for="item in favoriteList" 
        :key="item.dishId"
        @click="viewDishDetail(item.dishId)"
      >
        <image :src="item.imageUrl || '/static/images/default-dish.jpg'" class="dish-image" mode="aspectFill" />
        <view class="dish-info">
          <text class="dish-name">{{ item.dishName }}</text>
          <view class="dish-tags" v-if="item.cuisine || item.taste">
            <text class="tag cuisine" v-if="item.cuisine">{{ item.cuisine }}</text>
            <text class="tag taste" v-if="item.taste">{{ item.taste }}</text>
          </view>
          <view class="nutrition-info" v-if="item.calories || item.protein">
            <text class="nutrition-item" v-if="item.calories">🔥 {{ item.calories }}千卡</text>
            <text class="nutrition-item" v-if="item.protein">🥩 {{ item.protein }}g蛋白质</text>
          </view>
          <text class="favorite-time">收藏时间: {{ formatTime(item.favoriteTime) }}</text>
        </view>
        <view class="actions">
          <button class="remove-btn" @click.stop="removeFavorite(item)">
            取消收藏
          </button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <text class="empty-text">暂无收藏菜品</text>
      <button class="goto-recommend" @click="gotoRecommend">
        去推荐页面看看
      </button>
    </view>

    <!-- 加载更多 -->
    <uni-load-more :status="loadStatus" v-if="favoriteList.length > 0" />
  </view>
</template>

<script>
import { getFavoriteList, toggleFavorite } from '@/api/diet'

export default {
  data() {
    return {
      favoriteList: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      loadStatus: 'more'
    }
  },
  onLoad() {
    this.loadFavoriteList()
  },
  onReachBottom() {
    if (this.loadStatus === 'more') {
      this.loadMore()
    }
  },
  methods: {
    async loadFavoriteList() {
      try {
        this.loadStatus = 'loading'
        const userId = this.getUserId()
        console.log('📋 加载收藏列表 - 用户ID:', userId)
        
        const res = await getFavoriteList(userId, this.pageNum, this.pageSize)
        console.log('📥 收藏列表响应:', res)
        
        if (res.code === 200) {
          const processedData = (res.rows || []).map(item => {
            console.log('📊 处理收藏数据:', item)
            return {
              dishId: item.dishId,
              dishName: item.dishName || '菜品' + item.dishId,
              imageUrl: item.imgUrl ? `http://localhost:8080${item.imgUrl}` : '/static/images/default-dish.jpg',
              favoriteTime: item.createTime,
              cuisine: item.cuisine || '未知',
              taste: item.taste || '未知',
              calories: item.calories || 0,
              protein: item.protein || 0
            }
          })
          
          if (this.pageNum === 1) {
            this.favoriteList = processedData
          } else {
            this.favoriteList = [...this.favoriteList, ...processedData]
          }
          this.total = res.total || 0
          
          // 判断是否还有更多数据
          if (res.rows && res.rows.length < this.pageSize) {
            this.loadStatus = 'noMore'
          } else {
            this.loadStatus = 'more'
          }
        } else {
          this.loadStatus = 'more'
          uni.showToast({ title: '加载失败', icon: 'none' })
        }
      } catch (error) {
        console.error('❌ 加载收藏列表失败:', error)
        this.loadStatus = 'more'
        uni.showToast({ title: '加载失败', icon: 'none' })
      }
    },
    
    loadMore() {
      this.pageNum++
      this.loadFavoriteList()
    },
    
    async removeFavorite(item) {
      try {
        const userId = this.getUserId()
        console.log('🗑️ 取消收藏:', { dishId: item.dishId, userId })
        
        const result = await toggleFavorite(item.dishId, userId)
        console.log('✅ 取消收藏结果:', result)
        
        // 从列表中移除
        this.favoriteList = this.favoriteList.filter(fav => fav.dishId !== item.dishId)
        this.total = Math.max(0, this.total - 1)
        
        uni.showToast({
          title: '取消收藏成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('❌ 取消收藏失败:', error)
        uni.showToast({ 
          title: '操作失败', 
          icon: 'none' 
        })
      }
    },
    
    getUserId() {
      let userId = uni.getStorageSync('userId')
      if (!userId) {
        userId = 100
        uni.setStorageSync('userId', userId)
      }
      return Number(userId)
    },
    
    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    
    viewDishDetail(dishId) {
      uni.navigateTo({
        url: `/pages/diet/detail/index?id=${dishId}`
      })
    },
    
    gotoRecommend() {
      uni.switchTab({
        url: '/pages/diet/recommend/index'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.favorites-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: white;
  border-radius: 16rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.count {
  font-size: 24rpx;
  color: #666;
}

.favorite-item {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.dish-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.dish-info {
  flex: 1;
}

.dish-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.dish-tags {
  display: flex;
  margin-bottom: 8rpx;
}

.tag {
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  margin-right: 8rpx;
  
  &.cuisine {
    background: #e6f7ff;
    color: #1890ff;
  }
  
  &.taste {
    background: #f6ffed;
    color: #52c41a;
  }
}

.nutrition-info {
  display: flex;
  margin-bottom: 8rpx;
}

.nutrition-item {
  font-size: 20rpx;
  background: #f0f9ff;
  color: #0369a1;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  margin-right: 8rpx;
}

.favorite-time {
  font-size: 24rpx;
  color: #999;
}

.remove-btn {
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  display: block;
  margin-bottom: 40rpx;
}

.goto-recommend {
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 30rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}
</style>